// pages/user/user.js
const {
  getUser,getUserPost,delPost,getLikePosts,isLikePost,getUserById
} = require('../../apis/api')

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    testArray:[],
    msg1:'1',  
    noramalData: [],
    UserDataList:[],
    active: 0,
    loadingMore: false,
    huozan:"0",
    guanzhu:"0",
    fan:"0",
    show2:false,
    deleid:""
  },
  guanzhu(){
    wx.navigateTo({
      url: '/pages/user/guanzhu/guanzhu',
    })
  },  
  fensi(){
    wx.navigateTo({
      url: '/pages/user/fensi/fensi',
    })
  },
  /**
   * 跳转至setting页面
   */
  navigateToSettingPage() {
    wx.navigateTo({
      url: '/pages/setting/setting',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['username', 'userAvatar', 'email', 'token'],
      actions: ['setUsername', 'setUserAvatar', 'setEmail', 'setToken'],
    })
  },
  onClick(event){
    wx.showToast({
      title: `点击标签 ${event.detail.name}`,
      icon: 'none',
    });
    var that = this
    if(event.detail.name===1){
      wx.showLoading({  // 显示加载中loading效果 
        title: "加载中",
        mask: true  //开启蒙版遮罩
      });
      getLikePosts(this.data.token, (res) => {
        if(res.data.code===200){
          // this.setData({
          //   followData: res.data.data
          // })
          var arr = res.data.data.map((item) => {
            return new Promise((resolve) => {
              getUserById(this.data.token, item.post_owner_id, (res) => {
                if (res.data.code === 200) {
                  resolve({
                    ...item,
                    tx: res.data.data.pictureUrl,
                    name: res.data.data.userName,
                    love:true
                  });
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  });
                  resolve(item); // Return the original item in case of error.
                }
              });
            });
          });
          Promise.all(arr).then((updatedData) => {
            this.setData({
              noramalData: updatedData,
            });
            wx.hideLoading()

          });
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log(this.data)
    getUser(this.data.token,(res)=>{
      if(res.data.code === 200){
        this.setData({
          huozan:res.data.data.likes,
          guanzhu:res.data.data.followed_users,
          fan:res.data.data.fans
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
    var that = this
    wx.showLoading({  // 显示加载中loading效果 
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });
    getUserPost(this.data.token, (res) => {
      if (res.data.code === 200) {
        this.setData({
          UserDataList: res.data.data
        });
        const arr = this.data.UserDataList.map((item) => {
          return {
            ...item,
            tx: that.data.userAvatar,
            name: that.data.username
          };
        });
        this.setData({
          UserDataList: arr
        });
        // 在此处进行点赞信息的处理
        const likePromises = this.data.UserDataList.map((item) => {
          return new Promise((resolve) => {
            isLikePost(this.data.token, item.post_id, (res) => {
              if (res.data.code === 200) {
                resolve({
                  ...item,
                  love: res.data.data==='true'?true:false
                });
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                });
                resolve(item); // Return the original item in case of error.
              }
            });
          });
        });
    
        Promise.all(likePromises).then((updatedDataWithLikes) => {
          this.setData({
            UserDataList: updatedDataWithLikes,
          });
          // 数据更新后再输出
          wx.hideLoading()
          console.log(this.data.UserDataList);
        });
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
      }
    });
    
  },
  goDetail(e){
    wx.navigateTo({
      url: '/pages/detail/detail?nid='+e.currentTarget.dataset.nid,
    })
  },
  longpress(e){
      this.setData({
        show2: true,
        deleid: e.currentTarget.dataset.nid
      })
  },
  onClose2() {
    this.setData({ show2: false })
  },
  delete() {
    delPost(this.data.token,this.data.deleid, (res) => {
      if (res.data.code === 200) {
        this.setData({
          show2:false,
          deleid:""
        })
        this.onReady()
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onReady()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 展示加载框
    this.setData({
      loadingMore: true
    })

    // 加载数据


    // 取消加载框
    setTimeout(() => {
      let array = this.data.testArray
      array.push('orange')
      this.setData({
        testArray: array
      })
      this.setData({
        loadingMore: false
      })
    }, 1500);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})